/*
 * =====================================================================================
 *
 *       Filename:  task.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年05月08日 17时10分42秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "tbr_monitor.h"

static LIST_HEAD(head_monitor_task);
static pthread_mutex_t mutex_monitor_task = PTHREAD_MUTEX_INITIALIZER;
static int fd_pipe[2];
#define PIPE_RD 0
#define PIPE_WR 1

static void task_queue_active()
{
    write(fd_pipe[PIPE_WR], "w", 1);
}

static void task_queue_wait_active()
{
    char c;
    while(read(fd_pipe[PIPE_RD], &c, 1) > 0) {
        break;
    }
}

int tbr_monitor_task_init()
{
    int ret = pipe(fd_pipe);
    if(ret < 0) {
        debug_err("%s: [pipe]: %s\n", __func__, strerror(errno));
        return -1;
    }
    return ret;
}

void tbr_monitor_task_in(struct tbr_monitor_task *task)
{
    if(NULL == task) {
        return;
    }
    pthread_mutex_lock(&mutex_monitor_task);
    list_add_tail(&(task->list), &head_monitor_task);
    pthread_mutex_unlock(&mutex_monitor_task);
    task_queue_active();
}

struct tbr_monitor_task *tbr_monitor_task_out()
{
    task_queue_wait_active();
    struct list_head *tmp = NULL;
    pthread_mutex_lock(&mutex_monitor_task);
    if(list_empty(&head_monitor_task)) {
        tmp = NULL;
    }
    else {
        tmp = (&head_monitor_task)->next;
        list_del(tmp);
    }
    pthread_mutex_unlock(&mutex_monitor_task);
    return tmp?list_entry(tmp, struct tbr_monitor_task, list):NULL;
}


void tbr_monitor_task_free(struct tbr_monitor_task *task)
{
    free(task);
}

